<template>
  <div class="app-container">
    <div class="search-container">
      <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
        <el-form-item label="床号" prop="bedNo">
          <el-input v-model="queryParams.bedNo" class="width-120" clearable placeholder="请输入床号"
                    @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="床标号" prop="bedLabel">
          <el-input v-model="queryParams.bedLabel" class="width-120" clearable
                    placeholder="请输入床标号"
                    @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="房间" prop="roomNo">
          <el-input v-model="queryParams.roomNo" class="width-120" clearable placeholder="请输入房间"
                    @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="床位编制类型" prop="bedApprovedType">
          <el-select v-model="queryParams.bedApprovedType" class="width-120" clearable
                     placeholder="请选择床位编制类型"
                     @change="handleQuery">
            <el-option v-for="dict in dictDataMap['bed_approved_type_dict']" :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="男/女" prop="bedSexType">
          <el-select v-model="queryParams.bedSexType" class="width-120" clearable placeholder="请选择男/女"
                     @change="handleQuery">
            <el-option v-for="dict in dictDataMap['bed_sex']" :key="dict.dictValue" :label="dict.dictLabel"
                       :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="空床" prop="bedBlank">
          <el-radio-group v-model="queryParams.bedBlank" @change="handleQuery">
            <el-radio value="">全部</el-radio>
            <el-radio value="Y">占用</el-radio>
            <el-radio value="N">未占用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="包床标识" prop="bedOccupy">
          <el-radio-group v-model="queryParams.bedOccupy" @change="handleQuery">
            <el-radio value="">全部</el-radio>
            <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                      :value="dict.dictValue">{{
                dict.dictLabel
              }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="床位状态" prop="bedStatus">
          <el-radio-group v-model="queryParams.bedStatus" @change="handleQuery">
            <el-radio value="">全部</el-radio>
            <el-radio v-for="dict in dictDataMap['sys_normal_disable']" :key="dict.dictValue"
                      :value="dict.dictValue">{{
                dict.dictLabel
              }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="床位是否锁定" prop="lockStatus">
          <el-radio-group v-model="queryParams.lockStatus" @change="handleQuery">
            <el-radio value="">全部</el-radio>
            <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                      :value="dict.dictValue">{{
                dict.dictLabel
              }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button plain type="primary" @click="handleAdd">
          <template #icon>
            <i-ep-plus/>
          </template>
          新增
        </el-button>
      </el-col>
    </el-row>

    <el-table v-adaptive :border="true" :data="bedRecList" :header-cell-style="$headerCellStyle" :stripe="true"
              highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column :align="'center'" label="护理单元" prop="wardCodeName"/>
      <el-table-column :align="'center'" label="空床" prop="bedBlank">
        <template #default="scope">
          <el-tag v-if="scope.row.visitId" type="warning">占用</el-tag>
          <el-tag v-else type="primary">未占用</el-tag>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="床号" prop="bedNo">
        <template #default="scope">
          <span class="ys-css">{{ scope.row.bedNo }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="床标号" prop="bedLabel"/>
      <el-table-column :align="'center'" label="房间" prop="roomNo"/>
      <!-- <el-table-column label="所属科室代码" :align="'center'" prop="deptId" /> -->
      <el-table-column :align="'center'" label="床位编制类型" prop="bedApprovedType">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['bed_approved_type_dict']" :value="scope.row.bedApprovedType"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="男/女" prop="bedSexType">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['bed_sex']" :value="scope.row.bedSexType"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="床位等级" prop="bedGradeName" width="210"/>
      <el-table-column :align="'center'" label="空调等级" prop="airconditionClassName"/>
      <el-table-column :align="'center'" label="床位状态" prop="bedStatus">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_normal_disable']" :value="scope.row.bedStatus"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="包床标识" prop="bedOccupy">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.bedOccupy"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="床位是否锁定" prop="lockStatus">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.lockStatus"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="锁床位操作员" prop="lockOperator"/>
      <el-table-column :align="'center'" label="备注" prop="remarks"/>
      <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作" width="220">
        <template #default="scope">
          <el-button type="success" @click="handleUpdate(scope.row)">
            <template #icon>
              <i-ep-edit/>
            </template>
            修改
          </el-button>
          <el-button type="danger" @click="handleDelete(scope.row)">
            <template #icon>
              <i-ep-delete/>
            </template>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                :total="total" @pagination="getList"/>

    <!-- 添加或修改床位对话框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="房间" prop="roomNo">
          <el-input v-model="form.roomNo" placeholder="请输入房间"/>
        </el-form-item>
        <el-form-item label="床号" prop="bedNo">
          <el-input v-model="form.bedNo" placeholder="请输入床号" @blur="bedNoBlur"/>
        </el-form-item>
        <el-form-item label="床标号" prop="bedLabel">
          <el-input v-model="form.bedLabel" :disabled="true" placeholder="请输入床标号"/>
        </el-form-item>
        <el-form-item label="床位等级" prop="bedGradeName">
          <el-input v-if="isShow" v-model="form.bedGradeName"
                    @focus="isShowItemNameFocus()">
          </el-input>
          <automatic-completion v-else ref="itemAutomatic" v-model="form.bedGradeName" :dict-array="dictArray"
                                :table-body-list="tableBodyList" :table-head-list="tableHeadList" :title="itemTitle"
                                :width="660" style="width: 100%;"
                                @itemNameInput="itemNameInput" @rowClick="rowClick"/>
        </el-form-item>
        <el-form-item label="空调等级" prop="airconditionClass">
          <el-input v-model="form.airconditionClass" placeholder="请输入空调等级"/>
        </el-form-item>
        <el-form-item label="床位编制类型" prop="bedApprovedType">
          <el-select v-model="form.bedApprovedType" placeholder="请选择床位编制类型">
            <el-option v-for="dict in dictDataMap['bed_approved_type_dict']" :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="男/女" prop="bedSexType">
          <el-select v-model="form.bedSexType" placeholder="请选择男/女">
            <el-option v-for="dict in dictDataMap['bed_sex']" :key="dict.dictValue" :label="dict.dictLabel"
                       :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="床位状态">
          <el-radio-group v-model="form.bedStatus">
            <el-radio v-for="dict in dictDataMap['sys_normal_disable']" :key="dict.dictValue"
                      :value="dict.dictValue">{{
                dict.dictLabel
              }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="包床标识" prop="bedOccupy">
          <el-radio-group v-model="form.bedOccupy">
            <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                      :value="dict.dictValue">{{
                dict.dictLabel
              }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
export default {
  name: "BedRec"
}
</script>

<script setup lang="ts">
import {addBedRec, delBedRec, getBedRec, listBedRec, updateBedRec, selectPageBedRec} from "@/api/nurse/bedRec.ts";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
// 项目自动补全组件
import AutomaticCompletion from "@/components/AutomaticCompletion/index.vue";
import {jsonStrInObj, clinicTableHeadList} from "@/utils/autoComplete"
import {listClinicItemDict, getClinicItemDict, autoBuildQuery} from "@/api/base/clinicItemDict";

const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('bed_approved_type_dict', 'sys_normal_disable', 'sys_yes_no', 'bed_sex'))
const useUserStore = useUserStoreHook();
const {proxy} = getCurrentInstance() as any;
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const currentSelectDept = proxy.$currentSelectDept

// 项目选择自动补全窗体名称
const itemTitle = ref('选择项目')
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(clinicTableHeadList))
// 项目选择自动补全表格数据
const tableBodyList = ref([])
// 项目选择自动补全字典数组
const dictArray = ref(['bill_item_class_dict'])
const itemAutomatic = ref()
const formRef = ref();
const queryParamsRef = ref()
const bedRecList = ref([]);
const open = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  bedId: "",
  patientId: "",
  visitId: "",
  wardCode: currentSelectDept,
  bedLabel: "",
  roomNo: "",
  deptId: "",
  bedApprovedType: "",
  bedSexType: "",
  bedGrade: "",
  bedStatus: "",
  lockStatus: "",
  lockOperator: "",
  bedOccupy: "",
  airconditionClass: "",
  lastAcctDateTim: "",
  orgId: "",
  remarks: "",
  bedBlank: ""
})
const form = ref<any>({
  bedId: "",
  patientId: "",
  visitId: "",
  wardCode: currentSelectDept,
  bedNo: 0,
  bedLabel: "",
  roomNo: "",
  deptId: "",
  bedApprovedType: "1",
  bedSexType: "",
  bedGrade: "",
  bedStatus: "",
  lockStatus: "",
  lockOperator: "",
  bedOccupy: "N",
  airconditionClass: "",
  lastAcctDateTim: "",
  orgId: queryParams.value.orgId,
  remarks: ""
})
const rules = ref({
  roomNo: [
    {
      required: true, message: "房间不能为空", trigger: "blur"
    }
  ],
  bedNo: [
    {
      required: true, message: "床号不能为空", trigger: "blur"
    }
  ],
  bedLabel: [
    {
      required: true, message: "床标号不能为空", trigger: "blur"
    }
  ],
  bedGradeName: [
    {
      required: true, message: "床位等级不能为空", trigger: "change"
    }
  ],
  bedApprovedType: [
    {
      required: true, message: "床位编制类型不能为空", trigger: "change"
    }
  ],
  bedStatus: [
    {
      required: true, message: "床位不能为空", trigger: "change"
    }
  ],
})

/** 查询床位列表 */
function getList() {
  selectPageBedRec(queryParams.value).then((response: any) => {
    bedRecList.value = response.rows;
    total.value = response.total;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    bedId: "",
    patientId: "",
    visitId: "",
    wardCode: currentSelectDept,
    bedNo: "",
    bedLabel: "",
    roomNo: "",
    deptId: "",
    bedApprovedType: "1",
    bedSexType: "",
    bedGrade: "",
    bedStatus: "0",
    lockStatus: "N",
    lockOperator: "",
    bedOccupy: "N",
    airconditionClass: "",
    lastAcctDateTim: "",
    orgId: queryParams.value.orgId,
    remarks: ""
  };
  nextTick(() => {
    formRef.value.resetFields()
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  // proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.bedId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  if (!queryParams.value.orgId) {
    return ElMessage.error("请先选择机构")
  }
  open.value = true;
  reset();
  title.value = "添加床位";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  open.value = true;
  reset();
  const _bedId = row.bedId || ids.value
  getBedRec(_bedId).then((response: any) => {
    form.value = response.data;
    form.value.updateTime = null
    form.value.createTime = null
    form.value.createBy = ""
    form.value.updateBy = ""
    nextTick(() => {
      itemAutomatic.value.setItemName(form.value.bedGradeName)
    })
    title.value = "修改床位";
  });
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      if (form.value.bedId != "") {
        updateBedRec(form.value).then((response: any) => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
        });
      } else {
        addBedRec(form.value).then((response: any) => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _bedIds = row.bedId ||
    ids.value;
  ElMessageBox.confirm('是否确认删除床号为"' + row.bedNo + '"的数据项？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delBedRec(_bedIds).then(() => {
      getList();
      ElMessage.success("删除成功");
    })
  }).catch(() => {
  })
}

/** 项目名称自动补全检索 */
function itemNameInput(itemName) {
  form.value.itemInfo = itemName
  getListClinicItemDict()
}

/** 自动补全后台查询 */
function getListClinicItemDict() {
  if (form.value.itemInfo) {
    form.value.notInSelect = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
    // 是否过滤已存在的项目标记
    form.value.isFiltrationContrastExist = true
    autoBuildQuery(form.value).then(res => {
      tableBodyList.value = res.data
      // 打开自动补全弹出框
      itemAutomatic.value.init()
    })
  } else {
    tableBodyList.value = []
  }
}

/** 项目列表行点击事件 */
function rowClick(row) {
  itemAutomatic.value.closePopover();
  isShow.value = true
  form.value.bedGrade = row.clinicItemId
  form.value.bedGradeName = row.itemName
  tableBodyList.value = []
}

/*
* 自动补全上边input获得焦点事件
* @param _index
* @param row
*/
let isShow = ref(true);

function isShowItemNameFocus() {
  isShow.value = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(form.value.bedGradeName)
    itemAutomatic.value.focusInput()
  })
}


function bedNoBlur() {
  form.value.bedLabel = form.value.bedNo
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/bedRec/export', {
    ...queryParams.value
  }, `bedRec_${new Date().getTime()}.xlsx`)
}

queryParams.value.orgId = userInfo.orgId
getList();
</script>
